package com.retoc.oawx.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.retoc.oawx.domain.Meeting;
import com.retoc.oawx.exception.OAException;
import com.retoc.oawx.mapper.UserMapper;
import com.retoc.oawx.service.MeetingService;
import com.retoc.oawx.mapper.MeetingMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

/**
* @author retoc
* @description 针对表【tb_meeting(会议表)】的数据库操作Service实现
* @createDate 2022-05-01 20:00:13
*/
@Service
public class MeetingServiceImpl extends ServiceImpl<MeetingMapper, Meeting>
    implements MeetingService{
    @Autowired
    private MeetingMapper meetingMapper;

    @Autowired
    private UserMapper userMapper;

    @Value("${oawx.code}")
    private String code;

    @Value("${oawx.receiveNotify}")
    private String receiveNotify;

    @Value("${workflow.urla}")
    private String workflow;

    //新建会议
    @Override
    public void insertMeeting(Meeting meeting) {
        int row = meetingMapper.insertMeeting(meeting);
        if (row!=1){
            throw new OAException("会议添加失败");
        }

//        DateTime start = DateUtil.parseDate(meeting.getDate() + " " + meeting.getStart() + ":00");
//        DateTime end = DateUtil.parseDate(meeting.getDate() + " " + meeting.getEnd() + ":00");
//        long between = end.between(start, DateUnit.HOUR);

        //添加到工作流
        startMeetingWorkFlow(meeting.getUuid(),meeting.getCreatorId(),meeting.getDate());
    }

//    查询会议
    @Override
    public ArrayList<HashMap> searchMyMeetingByPage(HashMap param) {
        ArrayList<HashMap> list = meetingMapper.selectMeetingByCreator(param);
        String date=null;
        ArrayList result=new ArrayList<>();
        JSONArray array =null;
        for (HashMap map: list) {
            String temp = map.get("date").toString();
            if (!temp.equals(date)){
                date=temp;
                HashMap resultMap=new HashMap<>();
                resultMap.put("date",date);
                array = new JSONArray();
                resultMap.put("list", array);
                result.add(resultMap);
            }
            array.put(map);
        }
        return result;
    }

    @Override
    public Meeting searchMeetingByInstanceId(String instanceId) {
        return meetingMapper.searchMeetingByInstanceId(instanceId);
    }

    @Override
    public boolean isSameDeptMeeting(String uuid) {
        return meetingMapper.searchMeetingMembersInSameDept(uuid);
    }


    @Override
    public HashMap searchMeetingById(int meetingId) {
        HashMap meeting = meetingMapper.searchMeetingById(meetingId);
        ArrayList<HashMap> members = meetingMapper.searchMeetingMembers(meetingId);
        meeting.put("members", members);
        return meeting;
    }

    @Override
    public void updateMeetingInfo(HashMap param) {
        int id = (int) param.get("id");
        String date = param.get("date").toString();
        String start = param.get("start").toString();
        String instanceId = param.get("instanceId").toString();
//        int hours =(int) param.get("hours");
        HashMap oldMeeting = meetingMapper.searchMeetingById(id);
        String uuid = oldMeeting.get("uuid").toString();
        int creatorId = Integer.parseInt(oldMeeting.get("creatorId").toString());
        int row = meetingMapper.updateMeetingInfo(param);
        if (row != 1) {
            throw new OAException("会议更新失败");
        }
//        JSONObject json=new JSONObject();
//        json.set("instanceId", instanceId);
//        json.set("reason", "会议被修改");
////        json.set("uuid", uuid);
////        json.set("code", code);
//        String url = workflow + "/approve/DeleteProcessById";
//        HttpResponse resp = HttpRequest.post(url).header("content-type", "application/json").body(json.toString()).execute();
//        if (resp.getStatus() != 200) {
//            log.error("删除工作流失败");
//            throw new OAException("删除工作流失败");
//        }
        deleteMeetingById(id);
        startMeetingWorkFlow(uuid,creatorId,date);
    }

    @Override
    public void deleteMeetingById(int id) {
        HashMap meeting = meetingMapper.searchMeetingById(id);
        String uuid = meeting.get("uuid").toString();
        String instanceId = meeting.get("instanceId").toString();
        DateTime date = DateUtil.parse(meeting.get("date") + " " + meeting.get("start"));
        DateTime now = DateUtil.date();
        if (now.isAfterOrEquals(date.offset(DateField.MINUTE, -20))) {
            throw new OAException("距离开始时间不足20分钟，会议不能删除");
        }
        int row = meetingMapper.deleteMeetingById(id);
        if (row != 1) {
            throw new OAException("会议删除失败");
        }
        JSONObject json=new JSONObject();
        json.set("instanceId", instanceId);
        json.set("reason", "会议被修改");
//        json.set("uuid", uuid);
//        json.set("code", code);
        String url = workflow + "/approve/DeleteProcessById";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString()).execute();
        if (resp.getStatus() != 200) {
            log.error("删除工作流失败");
            throw new OAException("删除工作流失败");
        }
    }

    @Override
    public void approveMeetingByInstanceId(String instanceId) {
        meetingMapper.approveMeetingByInstanceId(instanceId);
    }

    private void startMeetingWorkFlow(String uuid, int creatorId, String date) {
        //如果申请人为经理，则不需要创建工作流，直接生成一个uuid并完成审批即可
        int gmId = userMapper.searchGmId();
        if (creatorId==gmId){
            HashMap param = new HashMap();
            param.put("uuid", uuid);
            param.put("instanceId", UUID.randomUUID().toString());

            HashMap param1 = new HashMap();
            param1.put("uuid", uuid);
            param1.put("status", 1);

            meetingMapper.updateMeetingInstanceId(param);
            meetingMapper.updateMeetingStatus(param1);
            return ;
        }
        int managerId = userMapper.searchDeptManagerId(creatorId);
        boolean sameDept = meetingMapper.searchMeetingMembersInSameDept(uuid);
        JSONObject json = new JSONObject();
        json.set("url", receiveNotify);
        json.set("createId", creatorId);
        json.set("managerId", managerId);
        json.set("gmId", gmId);
//        json.set("hours", hours);
        json.set("sameDept", sameDept?1:0);
        json.set("dates", date);
        json.set("types", "meeting");
//        HashMap info = userMapper.searchUserInfo(creatorId);
//        json.set("uuid", uuid);
//        json.set("openId", info.get("openId"));
//        json.set("code", code);
//        json.set("date", date);
//        json.set("start", start);
//        String[] roles = info.get("roles").toString().split(",");
//        if (!ArrayUtil.contains(roles, "总经理")) {
//            Integer managerId = userMapper.searchDeptManagerId(creatorId);
//            json.set("managerId", managerId);
//            Integer gmId = userMapper.searchGmId();
//            json.set("gmId", gmId);
//            boolean sameDept = meetingMapper.searchMeetingMembersInSameDept(uuid);
//            json.set("sameDept", sameDept);
//        }
//        String url = workflow + "/workflow/startMeetingProcess";
        String url = workflow + "/meeting/meetingRequest";
        HttpResponse resp = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString())
                .execute();
        if (resp.getStatus() == 200) {
            json = JSONUtil.parseObj(resp.body());
            String instanceId = json.getStr("instanceId");
            HashMap param = new HashMap();
            param.put("uuid", uuid);
            param.put("instanceId", instanceId);
            int row = meetingMapper.updateMeetingInstanceId(param);
            if (row!=1){
                throw new OAException("保存会议工作流失败");
            }
        }
    }
}




